package com.ccp.dev.qbdms.api.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ccp.dev.core.basic.base.BaseController;
import com.ccp.dev.core.util.AppUtil;
import com.ccp.dev.extend.model.ExtendSysFile;
import com.ccp.dev.qbdms.consts.ZhiLiangConst;
import com.ccp.dev.qbdms.model.BaseBusinessModel;
import com.ccp.dev.qbdms.model.CommonReportModel;
import com.ccp.dev.qbdms.service.AttachmentService;
import com.ccp.dev.qbdms.service.CommonalityService;
import com.ccp.dev.qbdms.webservice.cxf.CxfClient;
import com.google.common.collect.Lists;
import java.lang.reflect.Method;
import java.util.List;
import javax.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created by zzy on 2020/8/6.
 *
 * @Author zzy
 * @Date 2020/8/6
 * @describe 通用上报数据接口
 */
@RestController
@RequestMapping(ZhiLiangConst.URL_API + ZhiLiangConst.URL_VERSION)
public class CommonApiController extends BaseController {

    private static final Logger LOGGER = LoggerFactory.getLogger(CommonApiController.class);
    @Resource
    private CommonalityService commonalityService;
    @Resource
    private AttachmentService attachmentService;

    /**
     * 上报接口
     *
     * @param jsonstr
     * @return
     */
    @PostMapping("/{modelName}" + ZhiLiangConst.API_URL_REPORT)
    public Object report(@RequestBody String jsonstr, @PathVariable("modelName") String modelName) {
        try {
            //解析json
            JSONObject jsonobj = JSONObject.parseObject(jsonstr);
            // 判断是否包含附件
            boolean hasFile = jsonobj.containsKey(ZhiLiangConst.API_REPORT_PARA_LIST_FILE);
            List<ExtendSysFile> filelist = Lists.newArrayList();
            try {
                if (hasFile) {
                    JSONArray filelistjson = jsonobj
                        .getJSONArray(ZhiLiangConst.API_REPORT_PARA_LIST_FILE);
                    filelist = filelistjson.toJavaList(ExtendSysFile.class);
                }
            } catch (Throwable t) {
                LOGGER.error("CommonApiController-" + modelName + ZhiLiangConst.API_URL_REPORT
                    + "error cause by :" + t.getMessage());
            }

            // 获取上报参数,是一个list
            JSONArray listobj = jsonobj.getJSONArray(ZhiLiangConst.API_REPORT_PARA_LIST);
            modelName = CxfClient.getClassName(modelName);
            Class<?> clazz1 = Class.forName("com.ccp.dev.qbdms.model." + modelName);
            List<?> list = listobj.toJavaList(clazz1);

            Object service = AppUtil.getBean(modelName + ZhiLiangConst.SERVICE);
            Class<? extends Object> clazz = service.getClass();
            Method m;
            m = ReflectionUtils.findMethod(clazz, ZhiLiangConst.SAVEALL, List.class, List.class);
            ReflectionUtils.invokeMethod(m, service, list, filelist);
        } catch (Exception e) {
            e.printStackTrace();
            return fail("失败:"+e.getMessage());
        }
        return success("成功");
    }

    /**
     * 无需上报的接口
     *
     * @param jsonstr
     * @return
     */
    @PostMapping("/{modelName}" + ZhiLiangConst.API_URL_DONOT)
    public Object doNotReport(@RequestBody String jsonstr, @PathVariable("modelName") String modelName) {
        //解析json
        JSONObject jsonObj = JSONObject.parseObject(jsonstr);
        CommonReportModel rrm = jsonObj.toJavaObject(CommonReportModel.class);
        int result=commonalityService.doNotNeedReportLocal(rrm.getTableName(),rrm.getDataId(),rrm.getStatus());
        if (result>0) {
            return success("成功");
        }else{
            return fail("失败");
        }
    }

    /**
     * 退回待修改的接口
     *
     * @param jsonstr
     * @return
     */
    @PostMapping("/{modelName}" + ZhiLiangConst.API_URL_RETURNMOTIFY)
    public Object returnModify(@RequestBody String jsonstr, @PathVariable("modelName") String modelName) {
        //解析json
        JSONObject jsonObj = JSONObject.parseObject(jsonstr);
        CommonReportModel rrm = jsonObj.toJavaObject(CommonReportModel.class);
        int result=commonalityService.returnAndUpdateLocal(rrm.getTableName(),rrm.getDataId(),rrm.getStatus(),rrm.getReturnMsg());
        if (result>0) {
            return success("成功");
        }else{
            return fail("失败");
        }
    }

    /**
     * 评定接口
     *
     * @param jsonstr
     * @return
     */
    @PostMapping("/{modelName}" + ZhiLiangConst.API_URL_EVALUATE)
    public Object evaluate(@RequestBody String jsonstr, @PathVariable("modelName") String modelName) {
        if (!ZhiLiangConst.EVALUATE_MODULE.contains(modelName)){
            return fail("该模块没有评定功能");
        }
        try {
            //解析json
            JSONObject jsonobj = JSONObject.parseObject(jsonstr);
            // 获取评定参数,是一个list
            JSONObject data = jsonobj.getJSONObject("data");
            modelName = CxfClient.getClassName(modelName);
            Class<?> clazz1 = Class.forName("com.ccp.dev.qbdms.model." + modelName);
            BaseBusinessModel model = (BaseBusinessModel) data.toJavaObject(clazz1);
            Object service = AppUtil.getBean(modelName + ZhiLiangConst.SERVICE);
            Class<? extends Object> clazz = service.getClass();
            Method m = ReflectionUtils.findMethod(clazz, ZhiLiangConst.UPDATE, Object.class);
            ReflectionUtils.invokeMethod(m, service, model);
        } catch (Exception e) {
            e.printStackTrace();
            return fail("失败:"+e.getMessage());
        }
        return success("成功");
    }


    /**
     * 分级部署 下发接收 下级单位保存整条数据
     *
     * @param jsonstr
     * @return
     */
    @PostMapping("/{modelName}" + ZhiLiangConst.API_URL_ISSUE)
    public Object issue(@RequestBody String jsonstr, @PathVariable("modelName") String modelName) {
        if (!ZhiLiangConst.ISSUE_MODULE.contains(modelName)){
            return fail("该模块没有下发功能");
        }
        try {
            //解析json
            JSONObject jsonobj = JSONObject.parseObject(jsonstr);
            // 判断是否包含附件
            boolean hasFile = jsonobj.containsKey(ZhiLiangConst.API_REPORT_PARA_LIST_FILE);
            List<ExtendSysFile> filelist = Lists.newArrayList();
            try {
                if (hasFile) {
                    JSONArray filelistjson = jsonobj
                            .getJSONArray(ZhiLiangConst.API_REPORT_PARA_LIST_FILE);
                    filelist = filelistjson.toJavaList(ExtendSysFile.class);
                }
            } catch (Throwable t) {
                LOGGER.error("CommonApiController-" + modelName + ZhiLiangConst.API_URL_REPORT
                        + "error cause by :" + t.getMessage());
            }
            // 获取上报参数,是一个list
            JSONArray listobj = jsonobj.getJSONArray("data");
            modelName = CxfClient.getClassName(modelName);
            Class<?> clazz1 = Class.forName("com.ccp.dev.qbdms.model." + modelName);
            List<?> list = listobj.toJavaList(clazz1);

            Object service = AppUtil.getBean(modelName + ZhiLiangConst.SERVICE);
            Class<? extends Object> clazz = service.getClass();
            Method m = ReflectionUtils.findMethod(clazz, ZhiLiangConst.SAVEALL, List.class, List.class);
            ReflectionUtils.invokeMethod(m, service, list, filelist);
        } catch (Exception e) {
            e.printStackTrace();
            return fail("失败:" + e.getMessage());
        }
        return success("成功");
    }

    /**
     * 接收附件接口
     */
    @PostMapping(ZhiLiangConst.API_URL_RECEIVE_ATTACHMENT)
    public Object writeAttachment(@RequestBody String jsonStr) {
        try {
            //解析json
            JSONObject jsonObj = JSONObject.parseObject(jsonStr);
            // 判断是否包含附件
            List<ExtendSysFile> extendSysFileList = jsonObj
                .getJSONArray(ZhiLiangConst.API_REPORT_PARA_LIST_FILE)
                .toJavaList(ExtendSysFile.class);
            attachmentService.writeAttachment(extendSysFileList);
        } catch (Exception e) {
            e.printStackTrace();
            return fail("失败:" + e.getMessage());
        }
        return success("成功");
    }

}
